from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.shortcuts import redirect
from django import forms
from PIL import Image

from num.models import GoodNumbers


# Create your views here.
class MyForm(forms.Form):
    name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}))
    mobile = forms.CharField()
    password = forms.CharField()
def index(request):
    #搜索功能
    datas = GoodNumbers.objects.all()
    data_dict = {}
    value=request.GET.get('q')
    if value:
        data_dict['mobile__icontains'] = value                                #icontains忽略大小写
        queryset=GoodNumbers.objects.filter(**data_dict)
        return render(request, "index.html", {'queryset': queryset})
    return render(request,"index.html",{"datas":datas})

# class NumForm(forms.Form):
#     name=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
#     password=forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}))
#     mobile=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
def login(request):
    #登录功能
    global notice
    if request.method == "POST":
         name=request.POST.get("name")
         password=request.POST.get("password")
         mobile=request.POST.get("mobile")
         captcha=request.POST.get("captcha")
         print(name,password,mobile,captcha)
         if GoodNumbers.objects.filter(password=password,mobile=mobile,name=name):
            print("登录成功")
            notice = "登录成功"
            request.session["info"] ={'name':name, 'password':password, 'mobile':mobile}
            return render(request, "login.html", context={"notice": notice})
         else:
             print("登录成功")
             notice = "登录失败"
             return render(request, "login.html", context={"notice": notice})

    return render(request,"login.html")


def register(request):
    #注册功能
    global notice
    if request.method == "POST":
         name=request.POST.get("name")
         password=request.POST.get("password")
         mobile=request.POST.get("mobile")
         captcha=request.POST.get("captcha")
         print(name,password,mobile,captcha)
         if GoodNumbers.objects.filter(mobile=mobile):
            notice="用户存在"
            print("用户存在")
            return render(request, "register.html", context={"notice": notice})
         else:
            GoodNumbers.objects.create(name=name,password=password,mobile=mobile)
            print("注册成功")
            notice = "注册成功"
            return render(request, "register.html", context={"notice": notice})

    return render(request,"register.html")



def information(request):
    if request.method == "POST":
        img = request.files["avatar"]
        image = Image.open(img.stream)
        image.save("./static/images/1.png")
        avatar_path = "./static/images/1.png"
    return render(request,'information.html')